package top.jnaw.jee.pm.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import top.jnaw.jee.pm.model.Projects;
import top.jnaw.jee.pm.model.Tasks;
import top.jnaw.jee.pm.model.TasksUsers;
import top.jnaw.jee.pm.model.Users;
import top.jnaw.jee.utils.Dates;
import top.jnaw.jee.utils.Https;

public class TasksController extends Controller {

  private static int num = 0;

  /**
   * 获取任务基本信息
   */
//  @RequiresAuthentication
//  @RequiresPermissions({"tasks:get"})
  public void get() {

    final int tid = getParaToInt("tid", -1);
    Record tasks = new Record();
    if (tid > -1) {
      tasks = Tasks.findByTid(tid);
      List<Record> listuser = Tasks.getTaskUsers(tid);
      if (tasks != null) {
        int updateid = tasks.getInt("update_user");
        Users users = Users.dao.findById(updateid);
        if (users != null) {
          tasks.set("update_username", users.getName());
        }
        tasks.set("listuser", listuser);
      }
    }

    if (tasks != null) {
      renderJson(Https.success("查询成功", tasks));
    } else {
      renderJson(Https.failure("查询失败", ""));
    }
  }

  /**
   * 删除任务
   */
  public void rm() {

    final int tid = getParaToInt("tid", -1);
    boolean result = false;
    if (tid > -1) {
      Tasks tasks = Tasks.dao.findById(tid);
      if (tasks != null) {
        result = tasks.delete();
      }
    }

    if (result) {
      renderJson(Https.success("删除任务成功", ""));
    } else {
      renderJson(Https.failure("删除任务失败", ""));
    }
  }

  /**
   * 添加任务
   */
  public void add() {
    final String content = getPara("content", "");
    final String lead_time = getPara("lead_time", "");
    final int uid = getParaToInt("uid", -1);
    final int pid = getParaToInt("pid", -1);
    final int state = getParaToInt("state", -1);
    final String cuids = getPara("cuids", "");
    boolean result = false;
    if (StrKit.notBlank(content) && uid > -1 && pid > -1) {
      Tasks tasks = new Tasks();
      tasks.setContent(content);
      tasks.setPid(pid);
      tasks.setUid(uid);
      if (state > -1) {
        tasks.setState(state + "");
      }
      tasks.setUpdateUser(uid);
      if (StrKit.notBlank(lead_time)) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
          Date date = null;
          date = sdf.parse(lead_time);
          tasks.setLeadTime(date);
        } catch (ParseException e) {
          e.printStackTrace();
        }
        result = tasks.save();
        String[] stringsa = cuids.split(",");
        for (int i = 0; i < stringsa.length; i++) {
          int uids = Integer.parseInt(stringsa[i]);
          if (Users.dao.findById(uids) != null) {
            TasksUsers tasksUsers = new TasksUsers();
            tasksUsers.setTid(tasks.getId());
            tasksUsers.setUid(uids);
            tasksUsers.save();
          }
        }
      }

    }

    if (result) {
      renderJson(Https.success("添加成功", ""));
    } else {
      renderJson(Https.failure("添加失败", ""));
    }

  }

  /**
   * 修改任务 tid 任务id content 任务内容 lead_time 交付时间 uid 修改人id cuids 参与人ids  1,2,3 state 任务状态 0
   */
  @Before(Tx.class)
  public void set() throws Exception {
    final int tid = getParaToInt("tid", -1);
    final String content = getPara("content", "");
    final String lead_time = getPara("lead_time", "");
    final int uid = getParaToInt("uid", -1);
    final String cuids = getPara("cuids", "");
    final int state = getParaToInt("state", -1);

    boolean result = false;
    if (tid > -1 && uid > -1) {
      Tasks tasks = Tasks.dao.findById(tid);
      if (tasks != null) {
        if (StrKit.notBlank(content)) {
          tasks.setContent(content);
        }
        if (state > -1) {
          tasks.setState(state + "");
        }
        if (StrKit.notBlank(lead_time)) {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
          Date date = sdf.parse(lead_time);
          tasks.setLeadTime(date);

        }
        tasks.setUpdateUser(uid);
        tasks.setUpdateTime(Dates.now());

        result = tasks.update();
        if (StrKit.notBlank(cuids)) {
          String[] stringsa = cuids.split(",");
          Tasks.rmTaskUserByTid(tid);
//          int[] intTemp = new int[stringsa.length];
          for (int i = 0; i < stringsa.length; i++) {
            int uids = Integer.parseInt(stringsa[i]);
            if (Users.dao.findById(uids) != null) {
              TasksUsers tasksUsers = new TasksUsers();
              tasksUsers.setTid(tid);
              tasksUsers.setUid(uids);
              tasksUsers.save();
            }
          }
        }
      }

    }

    if (result) {
      renderJson(Https.success("修改成功", ""));
    } else {
      renderJson(Https.failure("修改失败", ""));
    }
  }

  /**
   * 查询所有任务
   */
  public void getList() {
    final int uid = getParaToInt("uid", -1);
    final int my = getParaToInt("my", 1);
    final int pid = getParaToInt("pid", -1);
    final String odtime = getPara("odtime", "");
    final int od = getParaToInt("od", -1);
    final int state = getParaToInt("state", -1);
    final int page = getParaToInt("page", 1);
    final int size = getParaToInt("size", PropKit.getInt("paginate_size", 10));
    Page<Record> list = null;

    list = Tasks.getList(pid, my, state, uid, odtime, od, page, size);
    JSONObject jsonObject = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    List<Record> recordList = list.getList();

    for (int a = 0; a < recordList.size(); a++) {
      Record record = recordList.get(a);
      int tid = record.getInt("id");
      int updateid = record.getInt("update_user");
      Users users = Users.dao.findById(updateid);

      if (users != null) {
        record.set("update_username", users.getName());
      }
      List<Record> listTaskuser = Tasks.getTaskUsers(tid);
      record.set("listuser", listTaskuser);

      int unameid = record.getInt("uid");
      Users users1 = Users.dao.findById(unameid);
      String uname = "";
      if (users1 != null) {
        uname = users1.getName();
      }
      record.set("uname", uname);

      jsonArray.add(record);
    }

    jsonObject.put("totalRow", list.getTotalRow());
    jsonObject.put("pageNumber", list.getPageNumber());
    jsonObject.put("lastPage", list.isLastPage());
    jsonObject.put("firstPage", list.isFirstPage());
    jsonObject.put("totalPage", list.getTotalPage());
    jsonObject.put("pageSize", list.getPageSize());
    jsonObject.put("list", jsonArray);

    renderJson(Https.success("查询成功", jsonObject));

  }


  public void addList() {
    final int uid = getParaToInt("uid", -1);
    final String taskText = getPara("taskText", "");

    num = 0;
    try {
      addListUtil(uid, taskText);
    } catch (Exception e) {
      e.printStackTrace();
    }

    String msg = "第 " + num  + " 条出现问题";
    renderJson(Https.success(msg, ""));
  }

  private void addListUtil(int uid, String taskText) {
    //添加事物
    Db.tx(
        new IAtom() {
          @Override
          public boolean run() throws SQLException {
            if (StrKit.notBlank(taskText)) {
              String[] s1 = taskText.split("#");
              for (int i = 0; i < s1.length; i++) {
                if (StrKit.notBlank(s1[i])) {
                  num++;
                  String[] s2 = s1[i].trim().split("\\^|@|\\*");
                  if (s2.length == 4) {
                    Tasks tasks = new Tasks();
                    tasks.setContent(s2[0].trim());
                    tasks.setUid(uid);
                    tasks.setUpdateUser(uid);

                    Projects projects = Projects.dao.findByName(s2[2].trim());
                    tasks.setPid(projects.getId());

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    Date date = null;
                    try {
                      date = sdf.parse(s2[3].trim());
                    } catch (ParseException e) {
                      e.printStackTrace();
                      return false;
                    }
                    tasks.setLeadTime(date);
                    tasks.setState("0");
                    tasks.save();

                    String[] s3 = s2[1].trim().split(",");
                    for (int b = 0; b < s3.length; b++) {
                      Record users = Users.getUserInfo2(s3[b].trim());
                      TasksUsers tasksUsers = new TasksUsers();
                      tasksUsers.setUid(users.getInt("id"));
                      tasksUsers.setTid(tasks.getId());
                      if (tasks.getId() > -1) {
                        tasksUsers.save();
                      }
                    }
                  }
                }
              }
            }
            return true;
          }
        }
    );

  }

}
